package com.easy.admin.system.test;

import cn.hutool.core.thread.ThreadFactoryBuilder;
import com.alibaba.fastjson.JSONArray;
import io.netty.channel.group.ChannelMatcher;
import org.apache.ibatis.annotations.SelectKey;
import sun.plugin2.util.SystemUtil;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.concurrent.*;

/**
 * @author wangbo
 * @deprecated nioSocketServer 服务端
 */
public class NioServerSocket {
    public static void main(String[] args) throws Exception {
        //1.打开serversocketChanell
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        //2.绑定监听地址

        InetSocketAddress address = new InetSocketAddress(9090);
        serverSocketChannel.socket().bind(address);
        //2.1设置为非阻塞模式
        serverSocketChannel.configureBlocking(false);

        //3.创建selector 启动线程
        Selector selector = Selector.open();

        //3.1创建Reactor线程，创建多路复用器并启动线程

        //4.将serverSocketChannel 注册到selector
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        //内部线程池处理当前消息
        ThreadFactory  socketHalderFactor = new ThreadFactoryBuilder()
                .setNamePrefix("nio-resivce").build();
        ExecutorService singThreadPool = new ThreadPoolExecutor(1,1,0L, TimeUnit.MICROSECONDS,
                new LinkedBlockingDeque<Runnable>(1024),socketHalderFactor,new ThreadPoolExecutor.AbortPolicy());
        singThreadPool.execute(() ->{
            try {
                while (true) {
                    if (selector.select(2000) <= 0) {
                        System.out.println("当前没有连接");
                    } else {
                        System.out.println("已连接");
                        Iterator<SelectionKey> selectionKeys = selector.selectedKeys().iterator();
                        while (selectionKeys.hasNext()) {
                            SelectionKey key = selectionKeys.next();
                            //处理新接入的请求
                            if (key.isValid()) {
                                if (key.isAcceptable()) {
                                    ServerSocketChannel sc = (ServerSocketChannel) key.channel();
                                    SocketChannel Scc = sc.accept();
                                    Scc.configureBlocking(false);
                                    Scc.register(selector, SelectionKey.OP_READ);
                                }
                                if (key.isReadable()) {
                                    SocketChannel sc = (SocketChannel) key.channel();
                                    ByteBuffer bf = ByteBuffer.allocate(1024);
                                    int radeC = sc.read(bf);

                                    if (radeC > 0) {
                                        bf.flip();
                                        System.out.println("接收到消息：" + new String(bf.array()));
                                    }
                                }
                                selectionKeys.remove();
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        singThreadPool.shutdown();
    }
}
